<?php
/**
 * 获取考试项目信息 API
 * 用于 add_violation.php 页面的动态加载功能
 */

// 开启会话
session_start();

// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 设置响应头
header('Content-Type: application/json; charset=utf-8');

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => '用户未登录'
    ]);
    exit();
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => '不支持的请求方法'
    ]);
    exit();
}

// 获取考试项目ID
$exam_id = intval($_GET['exam_id'] ?? 0);

if ($exam_id <= 0) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => '无效的考试项目ID'
    ]);
    exit();
}

try {
    // 数据库连接
    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

    // 查询考试项目信息
    $sql = "SELECT id, exam_name, exam_date, end_date, subject_count, status FROM exams WHERE id = ? AND status = 'active'";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception("准备查询语句失败: " . $conn->error);
    }

    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => '考试项目不存在或已被删除'
        ]);
        $stmt->close();
        $conn->close();
        exit();
    }

    $exam = $result->fetch_assoc();
    $stmt->close();

    // 返回成功响应
    echo json_encode([
        'success' => true,
        'data' => [
            'id' => intval($exam['id']),
            'exam_name' => $exam['exam_name'],
            'exam_date' => $exam['exam_date'],
            'end_date' => $exam['end_date'],
            'subject_count' => intval($exam['subject_count']),
            'status' => $exam['status']
        ],
        // 为了兼容前端代码，直接在根级别提供这些字段
        'exam_date' => $exam['exam_date'],
        'end_date' => $exam['end_date'],
        'subject_count' => intval($exam['subject_count'])
    ]);

} catch (Exception $e) {
    error_log("获取考试项目信息失败: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => '服务器内部错误'
    ]);
} finally {
    // 关闭数据库连接
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
}
?>